package com.jamlu.framework.utils;

import android.os.Looper;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by DMing at 2018/3/3 0003
 */

public class ThreadUtils {

    private static ThreadPoolExecutor executorService;

    private static void ensureInstance(){
        if (Looper.getMainLooper() != Looper.myLooper()){
            throw new IllegalStateException("Not UI Thread!");
        }
        if (executorService == null) {
            int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
            int KEEP_ALIVE_TIME = 1;
            TimeUnit KEEP_ALIVE_TIME_UNIT = TimeUnit.SECONDS;
            BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
            executorService = new ThreadPoolExecutor(NUMBER_OF_CORES, NUMBER_OF_CORES * 2, KEEP_ALIVE_TIME, KEEP_ALIVE_TIME_UNIT, taskQueue,
                    Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        }
    }

    public static void excRunnable(Runnable task){
        ensureInstance();
        executorService.execute(task);
    }

    public static <T> Future<T> excCallBack(Callable<T> task){
        ensureInstance();
        return executorService.submit(task);
    }

    public static void shutdown(){
        if (executorService != null){
            executorService.setMaximumPoolSize(0);
            executorService.shutdown();
            executorService = null;
        }
    }
}
